package com.kplzj.maptest.map.customView;


import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Path;
import android.util.AttributeSet;
import android.util.Log;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.ScaleGestureDetector;
import android.view.View;

import java.util.ArrayList;
import java.util.List;

public class CustomAreaView extends View {
    private List<Path> paths;
    private Paint paint;
    private Matrix matrix; // 用于应用平移和缩放变换
    private float scaleFactor = 1f; // 缩放因子
    private float scaleFactorCar = 1.0f; // 缩放因子
    private float translateX = 0f; // X轴平移量
    private float translateY = 0f; // Y轴平移量
    private GestureDetector gestureDetector;
    private ScaleGestureDetector scaleGestureDetector;
    List<Float> minXYList;
    List<String> colorList;

    Path path = null;
    /**
     * 小车绘制逻辑
     */
    private List<CarBean> pointFList;
    private float carX = 0f;
    private float carY = 0f;
    private float carRotation = 0f; // In degrees

    public CustomAreaView(Context context) {
        super(context);
        init(context);
    }

    public CustomAreaView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    public CustomAreaView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context);
    }

    private void init(Context context) {

        paint = new Paint(Paint.ANTI_ALIAS_FLAG);
        paint.setAlpha(64);
        matrix = new Matrix();
        gestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
            @Override
            public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
                translateX -= distanceX;
                translateY -= distanceY;
                invalidate();
                return true;
            }

            @Override
            public boolean onDoubleTap(MotionEvent e) {
                scaleFactor *= 1; // 或者可以设置为其他缩放逻辑
                scaleFactorCar *= 1;
                invalidate();
                return true;
            }
        });

        scaleGestureDetector = new ScaleGestureDetector(context, new ScaleGestureDetector.SimpleOnScaleGestureListener() {
            @Override
            public boolean onScale(ScaleGestureDetector detector) {
                scaleFactor *= detector.getScaleFactor();
                scaleFactorCar *= detector.getScaleFactor();
                invalidate();
                return true;
            }
        });
    }

    // 在这里处理触摸事件
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        gestureDetector.onTouchEvent(event);
        scaleGestureDetector.onTouchEvent(event);
        return true; // 表示事件被处理
    }

    public void setPaths(List<Path> paths2, XmlDataParser xmlDataParser) {

        paths = new ArrayList<>();
//        this.paths = paths2;
        this.minXYList = xmlDataParser.getFloatList();
        this.colorList = xmlDataParser.getSubAreaColor();

        for (int i = 0; i < xmlDataParser.getMapBeanList().size(); i++) {

//          Log.e("TagAB", "name: " + xmlDataParser.getMapBeanList().get(i).getName());
            for (int j = 0; j < xmlDataParser.getMapBeanList().get(i).getSubAreas().size(); j++) {

                if (j % 2 == 0) {

                    if (path != null) {
                        paths.add(path);
                        path = null;
                    }

//                    Log.e("TagAB", "type: " + xmlDataParser.getMapBeanList().get(i).getSubAreas().get(j).getType());

                    for (int k = 0; k < xmlDataParser.getMapBeanList().get(i).getSubAreas().get(j).getPoints().size(); k++) {

                        float x = xmlDataParser.getMapBeanList().get(i).getSubAreas().get(j).getPoints().get(k).getX() + (-minXYList.get(0));
                        float y = xmlDataParser.getMapBeanList().get(i).getSubAreas().get(j).getPoints().get(k).getY() + (-minXYList.get(1));

                        Log.e("TagAB", "x坐标：" + x + "   y坐标：" + y + "集合：" + xmlDataParser.getMapBeanList().get(i).getSubAreas().get(j).getPoints().size());

                        if (path == null) {
                            path = new Path();
                            path.moveTo(x, y);
                        } else {
                            path.lineTo(x, y);
                        }
                    }
                }
            }
        }
//
//        Log.e("TagAB","paths:"+paths.size());
        if (path != null) {
            path.close();
        }
      invalidate();
    }

    public void setPoints(List<CarBean> points) {

        this.pointFList = points;
        if (pointFList.get(0).getX() < pointFList.get(0).getY()) {
            carRotation = -90;
        }
        invalidate();
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        canvas.translate(0, 0);
        canvas.save();
//        canvas.translate(getWidth()/2, getHeight()/4);
        // 应用缩放和平移变换
        matrix.setScale(scaleFactor, scaleFactor);
        matrix.postTranslate(translateX, translateY);
        canvas.concat(matrix);
        paint.setStyle(Paint.Style.FILL);

        //地图模型
//        if (minXYList != null) {


//            Log.e("TagAB3","mapX:"+getWidth()/2+"   mapY:"+getHeight()/2);
//        }

        if (paths != null && colorList != null) {

            int colorNum = 0; // 用于遍历颜色列表
            for (Path path : paths) {

                if (colorNum < colorList.size()) {

                    int color = Color.parseColor(colorList.get(colorNum));
                    paint.setColor(color);
                    canvas.drawPath(path, paint);
                    colorNum++; // 移动到下一个颜色
                }
            }
        }
        canvas.restore();

        canvas.save();
        matrix.setScale(scaleFactorCar, scaleFactorCar);
        matrix.postTranslate(translateX, translateY);
        canvas.concat(matrix);
        //小车模型
//        canvas.translate(getWidth()/2, getHeight()/2);
        canvas.translate(carX, carY);
        canvas.rotate(carRotation);
        if (pointFList == null) {
            return;
        }

        for (int i = 0; i < pointFList.size(); i++) {

            paint.setStrokeWidth(0);
            paint.setColor(0xff000000);
            paint.setAntiAlias(true);
            paint.setStyle(Paint.Style.FILL_AND_STROKE);
            float startX = pointFList.get(i).getX();
            float startY = pointFList.get(i).getY();

            if (i < 23) {
                float stopX = pointFList.get(i + 1).getX();
                float stopY = pointFList.get(i + 1).getY();
                canvas.drawLine(startX, startY, stopX, stopY, paint);
            } else if (i == 24) {
                canvas.drawLine(pointFList.get(0).getX(), pointFList.get(0).getY(), pointFList.get(23).getX(), pointFList.get(23).getY(), paint);
            } else if (i == 25 || i == 27 || i == 29 || i == 31) {

                float scaleX = pointFList.get(0).getX();
                float scaleY = pointFList.get(0).getY();
//                if (scaleX > scaleY) {//TODO 横向车辆
//                  Log.e("TagAB","车辆横向");
//                    float left = pointFList.get(i).getX() + 20 / 2;
//                    float right = pointFList.get(i).getY() + 10 / 2;
//                    float top = pointFList.get(i).getX() - 20 / 2;
//                    float bottom = pointFList.get(i).getY() - 10 / 2;
//                    canvas.drawRect(left, right, top, bottom, paint);
//                } else {//TODO 纵向车辆
////                    Log.e("TagAB","车辆纵向");
//                    float left = pointFList.get(i).getX() - 10 / 2;
//                    float right = pointFList.get(i).getY() - 10 / 2;
//                    float top = pointFList.get(i).getX() + 10 / 2;
//                    float bottom = pointFList.get(i).getY() + 20 / 2;
//                    canvas.drawRect(left, right, top, bottom, paint);
//                }
            }
        }
        canvas.restore();
    }

    /**
     * 小车模型移动
     *
     * @param distance
     */
    public void moveCar(float distance) {

        //E  x坐标：0.5099945   y坐标：66.13281集合：6
        //x坐标：0.009994507   y坐标：66.13403集合：6
        //x坐标：0.0   y坐标：59.13794集合：6
        //x坐标：0.5   y坐标：59.136963集合：6
        //x坐标：0.5   y坐标：59.286865集合：6
        //x坐标：0.5099945   y坐标：65.98291集合：6
        //x坐标：16.706001   y坐标：66.2168集合：7
        //x坐标：16.206993   y坐标：66.211914集合：7
        //x坐标：16.208   y坐标：66.06201集合：7
        //x坐标：16.275002   y坐标：59.34082集合：7

        //2024-04-19 15:01:36.827 16156-16156 TagAB                   com.kplzj.myapplication              E  carX:7.0   carY:0.0
        //2024-04-19 15:01:36.859 16156-16156 TagAB                   com.kplzj.myapplication              E  carX:14.0   carY:0.0
        //2024-04-19 15:01:38.540 16156-16156 TagAB                   com.kplzj.myapplication              E  carX:21.0   carY:0.0
        //2024-04-19 15:01:38.555 16156-16156 TagAB                   com.kplzj.myapplication              E  carX:28.0   carY:0.0
        //2024-04-19 15:01:38.574 16156-16156 TagAB                   com.kplzj.myapplication              E  carX:35.0   carY:0.0
        //2024-04-19 15:01:38.591 16156-16156 TagAB                   com.kplzj.myapplication              E  carX:42.0   carY:0.0
        //2024-04-19 15:01:38.607 16156-16156 TagAB                   com.kplzj.myapplication              E  carX:49.0   carY:0.0
        //2024-04-19 15:01:38.623 16156-16156 TagAB                   com.kplzj.myapplication              E  carX:56.0   carY:0.0


//        if(carX > 1930){
//            carX = -50;
//        }

//        if (carY >900){
//            carY = -50;
//        }

//        if(carX < 0){
//            carX = 1920;
//        }

//        if (carY < 0){
//            carY = 1042;
//        }

//        if (pointFList.get(0).getX() < pointFList.get(0).getY()) {
//            carX += distance * Math.cos(Math.toRadians(carRotation + 90));
//            carY += distance * Math.sin(Math.toRadians(carRotation + 90));
//        } else {
//            carX += distance * Math.cos(Math.toRadians(carRotation));
//            carY += distance * Math.sin(Math.toRadians(carRotation));
//        }
        float newX = (float) (carX + distance * Math.cos(Math.toRadians(carRotation + (pointFList.get(0).getX() < pointFList.get(0).getY() ? 90 : 0))));
        float newY = (float) (carY + distance * Math.sin(Math.toRadians(carRotation + (pointFList.get(0).getX() < pointFList.get(0).getY() ? 90 : 0))));

//      if (newX >= 40 && newX <= getWidth() - 40 && newY >= 40 && newY <= getHeight() - 40) {

        carX = newX;
        carY = newY;
//        }
        Log.e("TagAB","carX:"+carX+"   carY:"+carY);
        invalidate();
    }

    /**
     * 小车模型转弯
     *
     * @param angle
     */
    public void rotateCar(float angle) {

        carRotation += angle;
        invalidate();
    }
}